<template>
  <div>
    <div class="container"></div>
    <div class="dashboard-container">
      <div class="app-container">
        <el-card class="lurucard" shadow="never">
          <div class="header">{{ questiontitle }}</div>

          <!-- 组件 -->
          <div class="body" shadow="never">
            <el-form
              :model="form"
              :rules="EtqRules"
              ref="ruleForm"
              label-width="100px"
              class="demo-ruleForm"
            >
              <el-form-item prop="subjectID" label="学 科" style="width: 100%">
                <el-select
                  @change="Disciplinelinkage"
                  v-model="form.subjectID"
                  style="width: 452.8px"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in subjectlist"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item prop="catalogID" label="目录">
                <el-select
                  style="width: 452.8px"
                  v-model="form.catalogID"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in cataloguetlist"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item prop="enterpriseID" label="企业">
                <el-select
                  style="width: 452.8px"
                  v-model="form.enterpriseID"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in enterpriselist"
                    :key="item.id"
                    :label="item.shortName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item prop="province" label="城市">
                <el-select
                  @change="Urbanlinkage"
                  v-model="form.province"
                  placeholder="请选择"
                  style="margin-right: 10px"
                >
                  <el-option
                    ref="b"
                    v-for="(item, index) in provinceslist"
                    :key="index"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>

                <!-- 城市第二个框 -->
                <el-select

                  v-model="form.city"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, index) in cityslist"
                    :key="index"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item prop="direction" label="方向">
                <el-select
                  style="width: 452.8px"
                  v-model="form.direction"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, index) in direction"
                    :key="index"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="题型">
                <el-radio-group v-model="form.questionType">
                  <el-radio
                    v-for="item in questionType"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    @change="Questiontypelinkage(item.value)"
                  >
                    {{ item.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="难 度">
                <el-radio-group v-model="form.difficulty">
                  <el-radio
                    v-for="item in difficulty"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item prop="question" label="题干">
                <quill-editor
                  v-model="form.question"
                  :options="editorOption"
                ></quill-editor>
              </el-form-item>

              <!-- 第二部分 -->

              <!-- 选项 -->

              <el-form-item label="选项" v-show="exist">
                <!-- 单选 -->
                <template v-if="form.questionType === '单选'">
                  <div
                    class="option_item"
                    v-for="item in form.options"
                    :key="item.code"
                  >
                    <el-radio
                      @change="radioChange"
                      class="optionsradio"
                      v-model="radio"
                      :label="item.code"
                      >{{ item.code }}:</el-radio
                    >
                    <el-input v-model="item.title" class="optionsinput" />
                    <el-upload
                      class="avatar-uploader"
                      action="#"
                      :img-url="item.img"
                      >上传图片<i class="el-icon-circle-close"></i
                    ></el-upload>
                  </div>
                </template>

                <!-- 多选 -->
                <template v-else>
                  <div
                    class="option_item"
                    v-for="item in form.options"
                    :key="item.code"
                  >
                    <el-checkbox
                      class="optionsradio"
                      v-model="item.isRight"
                      :label="item.code"
                      >{{ item.code }}:</el-checkbox
                    >
                    <el-input v-model="item.title" class="optionsinput" />
                    <el-upload
                      class="avatar-uploader"
                      action="#"
                      :img-url="item.img"
                      >上传图片<i class="el-icon-circle-close"></i
                    ></el-upload>
                  </div>
                </template>
              </el-form-item>

              <!-- 增加选项与答案按钮 -->
              <el-form-item v-show="exist">
                <!-- disabled控制按钮能否 -->
                <el-button
                  :disabled="addBtnlist"
                  @click="addoptions"
                  type="danger"
                  >增加选项与答案</el-button
                >
              </el-form-item>

              <el-form-item label="解析视频">
                <el-input v-model="form.videoURL"></el-input>
              </el-form-item>

              <el-form-item prop="answer" label="答案解析">
                <quill-editor v-model="form.answer" @blur="isanswer" :options="editorOption">
                </quill-editor>
              </el-form-item>

              <el-form-item label="题目备注">
                <el-input v-model="form.remarks" type="textarea"></el-input>
              </el-form-item>

              <el-form-item label="试题标签">
                <el-select
                  v-model="form.tags"
                  multiple
                  filterable
                  allow-create
                  default-first-option
                  placeholder="请选择试题标签"
                >
                  <el-option
                    v-for="item in tagslist"
                    :key="item.value"
                    :label="item.label"
                    :value="item.label"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <!-- 确认提交 -->
              <el-form-item>
                <el-button v-if="this.questiontitle==='试题录入'" @click="submission" type="primary"
                  >确认提交</el-button
                >

                <el-button v-else @click="submission" type="success"
                  >确认修改</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
// import hljs from 'highlight.js'

import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { simple as subjectlist } from '@/api/hmmm/subjects.js'
import { simple as cataloguetlist } from '@/api/hmmm/directorys.js'
import { list as enterpriselist } from '@/api/hmmm/companys.js'
import { provinces as allcitys, citys as morecitys } from '@/api/hmmm/citys.js'
import { direction, questionType, difficulty } from '@/api/hmmm/constants.js'
import { simple as fetchTags } from '@/api/hmmm/tags.js'
import {
  add as fetchAddQuestion,
  detail as fetchQuestionInfo,
  update as fetchUpdate
} from '@/api/hmmm/questions.js'

export default {
  components: {
    quillEditor
  },
  data () {
    return {
      questiontitle: '试题录入',
      // 富文本框配置
      editorOption: {
        modules: {
          toolbar: [
            // ['bold', 'italic', 'underline', 'strike'],
            // ['blockquote', 'code-block'],
            // [{ header: 1 }, { header: 2 }],
            // [{ list: 'ordered' }, { list: 'bullet' }],
            // [{ script: 'sub' }, { script: 'super' }],
            // [{ indent: '-1' }, { indent: '+1' }],
            // [{ direction: 'rtl' }],
            // [{ size: ['small', false, 'large', 'huge'] }],
            // [{ header: [1, 2, 3, 4, 5, 6, false] }],
            // [{ color: [] }, { background: [] }],
            // [{ font: [] }], [{ align: [] }],
            // ['clean', 'link', 'image', 'video'],
            // ['addBtn'],

            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }], // toggled buttons
            ['blockquote', 'code-block'],
            ['link', 'image', 'video'],
            ['addBtn']
          ]
          // syntax: {
          //   highlight: (text) => {
          //     return hljs.highlightAuto(text).value
          //   }
          // }
        },
        placeholder: '请输入正文'
      },

      form: {
        // 各项绑定数据项
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业

        province: '', // 城市1
        city: '', // 城市2

        direction: '', // 方向
        questionType: '单选', // 题型
        difficulty: '', // 难度

        // 选项
        options: [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ],
        videoURL: '', // 解析视频
        tags: '', // 试题标签
        remarks: '', // 题目备注

        // 富文本绑定内容
        question: '', // 题干
        answer: '' // 答案解析
      },
      //

      EtqRules: {
        // 学科
        subjectID: [{ required: true, message: '请输入学科', trigger: 'blur' }],
        // 目录
        catalogID: [{ required: true, message: '请输入目录', trigger: 'blur' }],
        //  企业
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'blur' }
        ],
        //  城市1
        province: [{ required: true, message: '请选择地区', trigger: 'change' }],
        // 城市2
        // aaa: [{ required: true, message: '请选择地区', trigger: 'change' }],
        // 方向
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        // 题干
        question: [
          { required: true, message: '请输入题干内容', trigger: 'change' }
        ],
        // 解析
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'change' }
        ]
      },

      addBtnlist: true,
      radio: '', // 单选的绑定值
      exist: true, // v-show数据

      // 初始化下拉列表数据
      subjectlist: '',
      cataloguetlist: '',
      enterpriselist: '',

      provinceslist: allcitys(),
      cityslist: '',

      direction: direction,
      questionType: questionType,
      difficulty: difficulty,

      // Singleandmultiplechoice: 1, // 控制选项改变的数据
      tagslist: '' // 试题标签数据
    }
  },

  async mounted () {
    this.getsubjectlist()
    this.getcataloguetlist()
    this.getenterpriselist()
    if (this.$route.query.id) {
      this.Databackfill()
    }
  },

  methods: {
    isanswer () {
      this.$refs.ruleForm.validateField('answer')
    },
    // 数据回显
    async Databackfill () {
      this.questiontitle = '修改试题'
      const res = await fetchQuestionInfo(this.$route.query.id)
      this.form = res.data
      this.dataprocessing()
    },
    // 数据回显的数据处理
    async  dataprocessing () {
      // 数字转为对应的文字
      this.difficulty.forEach(item => {
        if (item.value === Number(this.form.difficulty)) {
          this.form.difficulty = item.label
        }
      })
      this.questionType.forEach(item => {
        if (item.value === Number(this.form.questionType)) {
          this.form.questionType = item.label
        }
      })

      // 选中状态转为布尔型
      this.form.options.forEach(item => {
        item.isRight = Boolean(item.isRight)
      })
      // 单选时，获取当前选中选项的code
      if (this.form.questionType === '单选') {
        this.form.options.forEach(item => {
          if (item.isRight) this.radio = item.label
        })
      }
      // 选项重新排序
      this.form.options.sort(function (a, b) {
        const num1 = a.code.charCodeAt()
        const num2 = b.code.charCodeAt()
        return (num1 - num2)
      })
      // 获取city列表
      this.cityslist = morecitys(this.form.province)

      // 处理标签回显数据

      // 获取标签列表
      const tags = await fetchTags({ subjectID: this.form.subjectID })
      this.tagslist = tags.data
      if (this.form.tags.length > 0) {
        const tagsArr = this.form.tags.split(',')
        // 有人上传的是id拼接的字符串，有人上传的是文本拼接的字符串，这里需要处理一下
        // 如果是id拼接的字符串
        const labelArr = []

        this.tagslist.forEach(item => {
          if (tagsArr.includes(item.value)) {
            labelArr.push(item.label)
          }
        })

        this.form.tags = tagsArr.length === labelArr.length ? labelArr : tagsArr
      }
    },
    // 学科下拉菜单
    async getsubjectlist () {
      const res = await subjectlist()
      this.subjectlist = res.data
    },
    // 目录下拉菜单
    async getcataloguetlist () {
      const res = await cataloguetlist()
      this.cataloguetlist = res.data
    },
    // 企业下拉菜单
    async getenterpriselist () {
      const res = await enterpriselist()
      this.enterpriselist = res.data.items
    },

    Questiontypelinkage (data) {
      if (data === 1) {
        this.addBtnlist = true // 按钮可选
        this.form.questionType = '单选'
        this.form.options = [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ]
        this.exist = true
      } else if (data === 2) {
        this.addBtnlist = false
        this.form.questionType = '多选'
        this.exist = true
      } else {
        this.exist = false
      }
    },

    // 学科联动change事件
    async Disciplinelinkage (subjectid) {
      this.form.catalogID = ''
      this.form.tags = ''
      const tags = await fetchTags({ subjectID: subjectid })
      this.tagslist = tags.data
    },
    // 城市联动change事件
    Urbanlinkage (city) {
      // 形参获取选中的值,调用函数将这个值传入到pname形参中获取列表
      this.cityslist = morecitys(city)
    },

    // 增加选项
    addoptions () {
      const length = this.form.options.length
      // 大写字母A-Z对应的ASCII码值是65-90
      // 小写字母a-z对应的ASCII码值是97-122
      const letter = String.fromCharCode(65 + length)
      const option = {
        code: letter, // 代码
        title: '', // 标题
        img: '', // 图片URL
        isRight: false // 是否正确答案
      }
      this.form.options.push(option)
    },
    // 处理isright
    radioChange (val) {
      this.form.options.forEach((item) => {
        if (item.code === val) {
          item.isRight = true
        } else {
          item.isRight = false
        }
      })
    },

    // 点击提交
    submission () {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return // 验证不通过，则return
        //  1.发送请求,提交
        try {
          let tags = this.form.tags
          // 如果是数组，需要转为字符串
          if (tags instanceof Array) {
            tags = this.form.tags.length > 0 ? this.form.tags.join(',') : ''
          }

          if (this.questiontitle === '试题录入') {
            await fetchAddQuestion({ ...this.form, tags })
          } else {
            await fetchUpdate({ ...this.form, tags })
          }
          this.$message.success(this.questiontitle + '成功')
          this.$refs.ruleForm.resetFields()
          this.$router.push('/questions/list')
        } catch (error) {
          console.log(error)
        }

        // this.$router.push({ path: this.redirect || '/' })
      })
    }
  }
}
</script>

<style scoped lang="scss" >
.header {
  padding: 18px 20px;
  border-bottom: 1px solid #ebeef5;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

.body {
  padding: 20px;
  height: 100%;
}
::v-deep .ql-editor {
  height: 200px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  width: 100px;
  height: 60px;
  line-height: 60px;
  text-align: center;
  font-size: 14px;
  display: inline-block;
  // transform: translateX(10px);
  margin-left: 10px;
  position: relative;
}

::v-deep .el-icon-circle-close::before {
  font-size: 18px;
  position: absolute;
  bottom: 47px;
  left: 88px;
}

.optionsinput {
  width: 200px;
}

.option_item {
  margin-bottom: 10px;
}

// .optionsradio{
// width: 100%;
// height: 100%;
// }

.option_item {
  display: flex;
  justify-content: start;
  align-items: center;
  margin-bottom: 10px;
  ::v-deep .el-radio {
    width: 50px;
    margin-right: 1px;
  }

  ::v-deep .el-checkbox {
    width: 50px;
    margin-right: 1px;
  }
}
</style>
